
function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}
function createList(arr) {
  if(arr.length == 0)
    return null;
  let head = new ListNode(arr[0], null), headNode = head;
  for(let i = 1; i < arr.length; i++) {
    let temp = new ListNode(arr[i], null);
    head.next = temp;
    head = temp;
  }
  return headNode;
}
function showList(head) {
  while(head) {
    console.log(head.val);
    head = head.next;
  }
}
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
  // l1 = createList(l1), l2 = createList(l2);
  // 进位
  let flag = 0, tempValue;
  if(l1.val + l2.val >= 10) {
    tempValue = l1.val + l2.val - 10;
    flag = 1;
  } else {
    tempValue = l1.val + l2.val;
  }
  let head = new ListNode(tempValue, null), p = head;
  l1 = l1.next, l2 = l2.next;
  while(l1 && l2) {
    if(flag) {
      l1.val += 1;
      flag = 0;
    }
    let tempNode;
    tempValue = l1.val + l2.val;
    if(tempValue >= 10) {
      tempValue -= 10;
      flag = 1;
    }
    tempNode = new ListNode(tempValue, null);
    p.next = tempNode;
    p = p.next;
    l1 = l1.next;
    l2 = l2.next;
  }
  while(l1) {
    if(flag) {
      l1.val += 1;
      flag = 0;
    }
    if(l1.val >= 10) {
      l1.val -= 10;
      flag = 1;
    }
    let tempNode = new ListNode(l1.val, null);
    p.next = tempNode;
    p = p.next;
    l1 = l1.next;
  }
  while(l2) {
    if(flag) {
      l2.val += 1;
      flag = 0;
    }
    if(l2.val >= 10) {
      l2.val -= 10;
      flag = 1;
    }
    let tempNode = new ListNode(l2.val, null);
    p.next = tempNode;
    p = p.next;
    l2 = l2.next;
  }
  if(flag) {
    let tempNode = new ListNode(1, null);
    p.next = tempNode;
  }
  return head;
  // showList(head);

};
let l1 = [2,4,3], l2 = [5,6,4];
console.log(addTwoNumbers(l1, l2));
l1 = [0], l2 = [0];
console.log(addTwoNumbers(l1, l2));
l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9];
console.log(addTwoNumbers(l1, l2));
